﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Text.RegularExpressions;
using System.ComponentModel;
using SalaryChannel.TaskWebService;

namespace SalaryChannel
{
    public partial class ChannelAssignment : UserControl, IJobCtrl
    {
        private VW_TaskOn TaskOn;
        private int _stepID = -1;
        /// <summary>
        /// Step_ID	Task_ID	Step_Name
        ///1	1	发起任务
        ///2	1	县公司下达任务
        ///3	1	市场部审批
        ///4	1	县公司确认		
        /// </summary>
        private int StepID
        {
            get { return _stepID; }
            set
            {
                if (_stepID != value)
                {
                    if (value < 2 || value > 4)
                    {
                        App.MessageBox.ShowDialog("初始化的步骤ID不属于当前任务");
                        this.Visibility = Visibility.Collapsed;
                        return;
                    }
                    _stepID = value;
                   
                    if (_stepID == 2 || _stepID == 4)
                    {
                        CommitStack.Visibility = Visibility.Visible;
                        VerifyStack.Visibility = Visibility.Collapsed;
                        this.AssignGrid.Columns[3].IsReadOnly = false;
                        this.AssignGrid.Columns[4].IsReadOnly = false;
                        if (this.StepID == 2)
                        {
                            this.ConfirmBtn.Visibility = Visibility.Collapsed;
                        }
                        else
                        {
                            this.ConfirmBtn.Visibility = Visibility.Visible;
                        }
                        
                    }
                    else if (_stepID== 3)
                    {
                        CommitStack.Visibility = Visibility.Collapsed;
                        VerifyStack.Visibility = Visibility.Visible;
                        this.FileNameTB.Text = string.Empty;
                        this.AssignGrid.Columns[3].IsReadOnly = true;
                        this.AssignGrid.Columns[4].IsReadOnly = true;
                    }
                  
                }
            }
        }


        private List<Assignment> AssignList;

        private string LastUserID = string.Empty;

        public ChannelAssignment()
        {
            InitializeComponent();
            ServiceInstance.TaskService.GetChannelLastNewUserCompleted += new EventHandler<SalaryChannel.TaskWebService.GetChannelLastNewUserCompletedEventArgs>(TaskService_GetChannelLastNewUserCompleted);
            ServiceInstance.TaskService.UpdateChannelAssignCompleted += new EventHandler<SalaryChannel.TaskWebService.UpdateChannelAssignCompletedEventArgs>(TaskService_UpdateChannelAssignCompleted);
            this.YNCBox.SelectedIndex = 0;

            this.AssignGrid.RowEditEnded += new EventHandler<DataGridRowEditEndedEventArgs>(AssignGrid_RowEditEnded);
        }

        void AssignGrid_RowEditEnded(object sender, DataGridRowEditEndedEventArgs e)
        {
            if (e.EditAction == DataGridEditAction.Commit)
            {
                (e.Row.DataContext as Assignment).IsChanged = true;
            }
        }
       

        #region IJobCtrl 成员

        public void Initiallize(TaskWebService.VW_TaskOn taskOn)
        {

            this.TaskOn = taskOn;
            this.StepID = taskOn.Step_ID;

            this.MsgTB.Text = taskOn.Remark;
            if (AssignList != null)
            {
                AssignList.Clear();
            }
            else
            {
                AssignList = new List<Assignment>();
            }

            if (this.AssignGrid.ItemsSource != null)
            {
                this.AssignGrid.ItemsSource = null;
            }

            this.IsEnabled = true;
        }

        #endregion

        /// <summary>
        /// 县公司渠道管理员导入任务文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImportBtn_Click(object sender, RoutedEventArgs e)
        {
            if(this.StepID!=2)
            {
                return;
            }
            App.MessageBox.ShowDialog("导入的TXT文件，每行为渠道编号和任务，用TAB键分开！", 
                new Action(DoImport),Title.Information);
        }
        void DoImport()
        {
            OpenFileDialog fDialog = new OpenFileDialog();
            fDialog.Filter = "文本文件(*.txt)|*.txt";
            fDialog.Multiselect = false;
            if (fDialog.ShowDialog().Value)
            {
                try
                {
                    if (this.AssignList.Count > 0)
                    {
                        this.AssignList.Clear();
                        
                    }
                    this.AssignGrid.ItemsSource = null;

                    this.FileNameTB.Text = fDialog.File.Name;
                    //dataFI = fDialog.File;
                    using (StreamReader reader = new StreamReader(fDialog.File.OpenRead()))
                    {
                        while (!reader.EndOfStream)
                        {
                            string line = reader.ReadLine();
                            if (string.IsNullOrEmpty(line))
                            {
                                continue;
                            }
                            string[] cols = line.Split(new char[] { (char)9 }, StringSplitOptions.RemoveEmptyEntries);
                            if (cols.Length != 2 
                                || cols[0].Length!=8
                                || cols[1].Length == 0)
                            {
                                App.MessageBox.ShowDialog(string.Format("导入数据格式有误，行：{0}" , this.AssignList.Count + 1));
                                this.AssignList.Clear();                                
                                return;
                            }
                            
                            int assign ;
                            if (!int.TryParse(cols[1], out assign))
                            {
                                App.MessageBox.ShowDialog(string.Format("渠道任务必须是整数！行：", this.AssignList.Count + 1));
                                this.AssignList.Clear();
                                return;
                            }
                            if (assign < 1)
                            {
                                App.MessageBox.ShowDialog(string.Format("渠道任务必须是大于零！行：", this.AssignList.Count + 1));
                                this.AssignList.Clear();
                                return;
                            }
                            this.AssignList.Add(new Assignment
                            {
                                ChannelID = cols[0],
                                Assign = int.Parse(cols[1])
                            });
                        }
                    }

                }
                catch (Exception ex)
                {
                    App.MessageBox.ShowDialog("导入数据失败：" + ex.Message, Title.Error);
                    return;
                }
                if (AssignList.Count == 0)
                {
                    return;
                }
                this.loading.Show();
                this.AssignGrid.ItemsSource = this.AssignList;
                chIndex =0;
                try
                {
                    ServiceInstance.TaskService.GetChannelLastNewUserAsync(this.TaskOn.Task_Month, this.AssignList[chIndex].ChannelID);
                }
                catch (Exception ex)
                {
                    
                     App.MessageBox.ShowDialog("查询数据失败：" + ex.Message, Title.Error);
                     this.loading.Stop();
                    return;
                }
                this.IsEnabled = false;
            }

        }
        int chIndex = 0;
        static Regex assignRegex = new Regex(@"^\[area\](?<Area>\d{4})\[name\](?<Name>\w*)\[users\](?<Users>\d*)$");

        void TaskService_GetChannelLastNewUserCompleted(object sender, SalaryChannel.TaskWebService.GetChannelLastNewUserCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null || !assignRegex.IsMatch(e.Result))
                {
                    throw new Exception("服务器查询失败");
                }
                 this.AssignList[chIndex].AreaCode=assignRegex.Match(e.Result).Result("${Area}");

                this.AssignList[chIndex].ChannelName = assignRegex.Match(e.Result).Result("${Name}");
                this.AssignList[chIndex].LastMonNewUsers = int.Parse(assignRegex.Match(e.Result).Result("${Users}"));

                if (chIndex == this.AssignList.Count - 1)
                {//查询最后一个
                    this.loading.Stop();
                    this.IsEnabled = true;
                }
                else
                {
                    ServiceInstance.TaskService.GetChannelLastNewUserAsync(this.TaskOn.Task_Month, this.AssignList[++chIndex].ChannelID);
                }
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("查询数据失败：" + ex.Message, Title.Error);
                this.loading.Stop();
                this.IsEnabled = true;
                return;
            }
        }

        /// <summary>
        /// 提交任务供审批
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommitBtn_Click(object sender, RoutedEventArgs e)
        {
            App.MessageBox.ShowDialog("是否确认提交审批？",new Action(DoCommit),Title.Information);
           
        }
        void DoCommit()
        {
            chIndex = 0;
            while (!(this.AssignList[chIndex].AreaCode == App.CurrentUser.CountyCode
                &&this.AssignList[chIndex].IsChanged))
            {
                chIndex++;
                if (chIndex >= this.AssignList.Count)
                {
                    return;
                }
            }
            try
            {
                ServiceInstance.TaskService.UpdateChannelAssignAsync(this.TaskOn.Task_Month,
                        this.AssignList[chIndex].ChannelID,
                        this.AssignList[chIndex].Assign,
                        this.AssignList[chIndex].Remark);
            }
            catch 
            {
                App.MessageBox.ShowDialog("连接服务器失败");
                return;
            }
            this.loading.Show();
            this.IsEnabled = false;
        }

        void TaskService_UpdateChannelAssignCompleted(object sender, SalaryChannel.TaskWebService.UpdateChannelAssignCompletedEventArgs e)
        {
            try
            {
                if (e.Result == false)
                {
                    this.IsEnabled = true;

                }
                else
                {
                    if (chIndex == this.AssignList.Count - 1)
                    {//查询最后一个
                      
                        ServiceInstance.TaskService.GetIntoNextStepCompleted += new EventHandler<SalaryChannel.TaskWebService.GetIntoNextStepCompletedEventArgs>(TaskService_GetIntoNextStepCompleted);

                        ServiceInstance.TaskService.GetIntoNextStepAsync(this.TaskOn.Flow_ID, this.MsgTB.Text);
                    }
                    else
                    {
                        chIndex++;
                        while (!(this.AssignList[chIndex].AreaCode == App.CurrentUser.CountyCode
                             && this.AssignList[chIndex].IsChanged))
                        {
                            chIndex++;
                            if (chIndex >= this.AssignList.Count)
                            {
                                ServiceInstance.TaskService.GetIntoNextStepCompleted += new EventHandler<SalaryChannel.TaskWebService.GetIntoNextStepCompletedEventArgs>(TaskService_GetIntoNextStepCompleted);

                                ServiceInstance.TaskService.GetIntoNextStepAsync(this.TaskOn.Flow_ID, this.MsgTB.Text);
                                return;
                            }
                        }
                        ServiceInstance.TaskService.UpdateChannelAssignAsync(this.TaskOn.Task_Month,
                        this.AssignList[chIndex].ChannelID,
                        this.AssignList[chIndex].Assign,
                        this.AssignList[chIndex].Remark);
                    }
                }
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("查询数据失败：" + ex.Message, Title.Error);
                this.loading.Stop();
                this.IsEnabled = true;
                return;
            }   
        }

        void TaskService_GetIntoNextStepCompleted(object sender, SalaryChannel.TaskWebService.GetIntoNextStepCompletedEventArgs e)
        {
            ServiceInstance.TaskService.GetIntoNextStepCompleted -= new EventHandler<SalaryChannel.TaskWebService.GetIntoNextStepCompletedEventArgs>(TaskService_GetIntoNextStepCompleted);
            try
            {
                if (e.Result)
                {
                    App.MessageBox.ShowDialog("操作成功！");
                    
                }
                else
                {
                    App.MessageBox.ShowDialog("操作失败！", Title.Error);
                    this.IsEnabled = true;
                }
            }
            catch
            {

                App.MessageBox.ShowDialog("操作失败！", Title.Error);
                this.IsEnabled = true;
            }
            this.loading.Stop();
            
        }

        /// <summary>
        /// 市管理员审批任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void VerifyBtn_Click(object sender, RoutedEventArgs e)
        {
            if (YNCBox.SelectedItem == null)
            {
                App.MessageBox.ShowDialog("请指定是否通过审批");
                return;
            }
            if (YNCBox.SelectedIndex==1
                && string.IsNullOrEmpty(MsgTB.Text))
            {
                App.MessageBox.ShowDialog("请输入不通过的原因");
                return;
            }

            if (YNCBox.SelectedIndex == 1)
            {
                ServiceInstance.TaskService.GetBackToLastStepCompleted += new EventHandler<SalaryChannel.TaskWebService.GetBackToLastStepCompletedEventArgs>(TaskService_GetBackToLastStepCompleted);
                ServiceInstance.TaskService.GetBackToLastStepAsync(this.TaskOn.Flow_ID, "[不通过]" + MsgTB.Text);

            }
            else if (YNCBox.SelectedIndex == 0)
            {
                ServiceInstance.TaskService.GetIntoNextStepCompleted += new EventHandler<SalaryChannel.TaskWebService.GetIntoNextStepCompletedEventArgs>(TaskService_GetIntoNextStepCompleted);

                ServiceInstance.TaskService.GetIntoNextStepAsync(this.TaskOn.Flow_ID, "[通过]" + this.MsgTB.Text);
                
            }
            

        }

        void TaskService_GetBackToLastStepCompleted(object sender, SalaryChannel.TaskWebService.GetBackToLastStepCompletedEventArgs e)
        {
            ServiceInstance.TaskService.GetBackToLastStepCompleted -= new EventHandler<SalaryChannel.TaskWebService.GetBackToLastStepCompletedEventArgs>(TaskService_GetBackToLastStepCompleted);
            try
            {
                if (e.Result)
                {
                    App.MessageBox.ShowDialog("操作成功！");
                    this.IsEnabled = false;
                }
                else
                {
                    App.MessageBox.ShowDialog("操作失败！", Title.Error);
                }
            }
            catch
            {

                App.MessageBox.ShowDialog("操作失败！", Title.Error);
            }
            
        }

        private void ConfirmBtn_Click(object sender, RoutedEventArgs e)
        {
            App.MessageBox.ShowDialog("结果确认后将无法悠，是否继续？",
                new Action(DoConfirm), Title.Information);
        }

        void DoConfirm()
        {
           
            ServiceInstance.TaskService.GetIntoNextStepCompleted += new EventHandler<SalaryChannel.TaskWebService.GetIntoNextStepCompletedEventArgs>(TaskService_GetIntoNextStepCompleted);
            try
            {   ServiceInstance.TaskService.GetIntoNextStepAsync(this.TaskOn.Flow_ID, this.MsgTB.Text);
            }
            catch
            {
                ServiceInstance.TaskService.GetIntoNextStepCompleted -= new EventHandler<SalaryChannel.TaskWebService.GetIntoNextStepCompletedEventArgs>(TaskService_GetIntoNextStepCompleted);
                App.MessageBox.ShowDialog("操作失败");
            }
                                
        }

        /// <summary>
        /// 查询本月渠道任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryBtn_Click(object sender, RoutedEventArgs e)
        {
            string User = string.Empty;
            if (this.StepID == 2 || this.StepID == 4)
            {
                User = App.CurrentUser.UserID;
            }
            else
            {
                User = App.GetID(TaskOn.LastUser).ToString();
            }

            try
            {
                ServiceInstance.TaskService.GetChannelAssignmentCompleted += new EventHandler<GetChannelAssignmentCompletedEventArgs>(TaskService_GetChannelAssignmentCompleted);
                ServiceInstance.TaskService.GetChannelAssignmentAsync(this.TaskOn.Task_Month, User);
            }
            catch 
            {
                App.MessageBox.ShowDialog("连接服务器失败",Title.Error);
                return;
              
            }
            this.loading.Show();
            if (this.AssignGrid.ItemsSource != null)
            {
                this.AssignGrid.ItemsSource = null; 
            }
            this.IsEnabled = false;

        }

        void TaskService_GetChannelAssignmentCompleted(object sender, GetChannelAssignmentCompletedEventArgs e)
        {
            ServiceInstance.TaskService.GetChannelAssignmentCompleted -= new EventHandler<GetChannelAssignmentCompletedEventArgs>(TaskService_GetChannelAssignmentCompleted);
            this.loading.Stop();
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取查询结果失败");

                }
                else
                {

                    foreach (string str in e.Result)
                    {
                        if (string.IsNullOrEmpty(str)
                            || !caRegex.IsMatch(str))
                        {
                            App.MessageBox.ShowDialog("获取查询结果失败");
                            return;
                        }

                        Assignment a = new Assignment
                        {
                            AreaCode = caRegex.Match(str).Result("${Area}"),
                            ChannelID = caRegex.Match(str).Result("${ID}"),
                            ChannelName = caRegex.Match(str).Result("${Name}"),
                            Remark = caRegex.Match(str).Result("${Remark}"),
                            IsIgnoreAreaCode = true,
                            IsChanged = false
                        };
                        a.LastMonNewUsers = int.Parse(caRegex.Match(str).Result("${Last}"));
                        a.Assign = int.Parse(caRegex.Match(str).Result("${Assign}"));
                        this.AssignList.Add(a);
                    }
                    this.AssignGrid.ItemsSource = this.AssignList;
                }
            }
            catch 
            {
                App.MessageBox.ShowDialog("获取查询结果失败");
            }
            this.IsEnabled = true;
        }

        static Regex caRegex = new Regex(@"^\[area\](?<Area>\d{4})\[id\](?<ID>\d{8})\[name\](?<Name>.+)\[last\](?<Last>\d+)\[assign\](?<Assign>\d+)\[remark\](?<Remark>.*)$");
    }

    public class Assignment : INotifyPropertyChanged
    {
        private string _areaCode = string.Empty;

        public string AreaCode
        {
            get { return _areaCode; }
            set 
            {
                if (_areaCode != value)
                {
                    _areaCode = value;
                    OnPropertyChanged("AreaCode");
                    if (_areaCode != App.CurrentUser.CountyCode)
                    {
                        this.Remark = "非本县区渠道，此行将不会提交";
                    }
                }
            }
        }


        private string _channelID=string.Empty;

        public string ChannelID 
        {
            get { return _channelID; }
            set
            {
                if (_channelID != value)
                {
                    _channelID = value;
                    OnPropertyChanged("ChannelID");
                }
            }
        }

        private string _channelName=string.Empty;

        public string ChannelName 
        {
            get { return _channelName; }
            set
            {
                if (_channelName != value)
                {
                    _channelName = value;
                    OnPropertyChanged("ChannelName");
                }
            }
        }

        private int _lastMonNewUsers=-1;
        public int LastMonNewUsers 
        {
            get
            {
                return _lastMonNewUsers;
            }

            set
            {
                if (_lastMonNewUsers != value)
                {
                    _lastMonNewUsers = value;
                    OnPropertyChanged("LastMonNewUsers");
                    UpdateVerify();
                }
            }
        }
        private int _assign=int.MinValue;
        public int Assign
        {
            get { return _assign; }
            set
            {
                if (_assign != value)
                {
                    _assign = value;

                    OnPropertyChanged("Assign");
                    UpdateVerify();
                   
                }
            }
        }
        private bool _isIgnoreAreaCode = false;

        public bool IsIgnoreAreaCode
        {
            get { return _isIgnoreAreaCode; }
            set { _isIgnoreAreaCode = value; }
        }
       
        void UpdateVerify()
        {
            if (IsIgnoreAreaCode || _areaCode == App.CurrentUser.CountyCode)
            {
                if (LastMonNewUsers != 0 && (float)this.Assign / (float)this.LastMonNewUsers < App.AssignmentPercent)
                {
                    this.Verify = string.Format("警告：任务小于上月发展量的{0}", App.AssignmentPercent.ToString("P")); ;
                }
                else
                {
                    this.Verify = string.Empty;
                }
            }
        }
        private string _remark=string.Empty;
        public string Remark
        {
            get { return _remark; }
            set
            {
                if (_remark != value)
                {
                    _remark = value;
                    OnPropertyChanged("Remark");
                }
            }
        }

        private string _Verify = string.Empty;

        public string Verify
        {
            get { return _Verify; }
            set
            {
                if (_Verify != value)
                {
                    _Verify = value;
                    OnPropertyChanged("Verify");
                }
            }
        }

        private bool _isChanged = true;

        public bool IsChanged
        {
            get { return _isChanged; }
            set { _isChanged = value; }
        }
    
        #region INotifyPropertyChanged 成员

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }



        #endregion
    }
}
